package cn.tedu.medicalmanagementsystem.base.exception;

import cn.tedu.medicalmanagementsystem.base.response.JsonResult;
import cn.tedu.medicalmanagementsystem.base.response.StatusCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolationException;

//@ControllerAdvice
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler
    //@ResponseBody
    public JsonResult doHandleIllegalArgumentException(IllegalArgumentException ex) {
        String data = ex.getMessage();
        log.error("doHandleIllegaArgumentException:"+data);
        return new JsonResult(StatusCode.OPERATION_FAILED, data);
    }

    @ExceptionHandler
    public JsonResult doHandleRuntimeException(RuntimeException ex){
        String data = ex.getMessage();
       log.error("doHandleRuntimeException:" + data);

       return new JsonResult(StatusCode.OPERATION_FAILED, data);
   }

    @ExceptionHandler
    public JsonResult doHandlerMethodArgumentNotValidException(MethodArgumentNotValidException ex){
        String data = ex.getFieldError().getDefaultMessage();
        log.error("doHandlerMethodArgumentNotValidException:"+data);
        return new JsonResult(StatusCode.VALIDATED_ERROR  ,data);
    }

    @ExceptionHandler
    public JsonResult doHandleConstraintViolationException(ConstraintViolationException ex){
        //String data = ex.getConstraintViolations().iterator().next().getMessage();
        String data = ex.getMessage().split(":")[1].trim();
        log.error("doHandleConstraintViolationException:"+data);
        return new JsonResult(StatusCode.VALIDATED_ERROR  ,data);
    }

    /**
     *第三个异常处理方法：可以处理所有的异常的处理方法
     */
    @ExceptionHandler
    public JsonResult doHandleThrowable(Throwable ex){
        String data = ex.getMessage();
        log.error("doHandleThrowable:" + data);
        return new JsonResult(StatusCode.THROWABLE_ERROR, data);
    }
}
